﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.Extensions;

namespace ConsoleApp1
{
    public class ImageHelper
    {
        private static readonly string dir = AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar;

        public static string SaveScreenShot(IWebDriver _webDriver, string dirname)
        {
            var dname = string.Empty;
            if (dirname.IndexOf("article-", StringComparison.Ordinal) <= 0)
            {
                throw new NullReferenceException("URL错误");
            }
            else
            {
                dname = dirname.Substring(dirname.IndexOf("article-", StringComparison.Ordinal));
            }

            if (!Directory.Exists(dir + "screenshot"))
            { 
                Directory.CreateDirectory(dir + "screenshot");
            }

            var filename = dir + "screenshot"+Path.DirectorySeparatorChar + dname +  ".png";
                try
                {
                    GetEntereScreenshot(_webDriver);
                    return filename;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            
        }

        public static string SaveImage(string Url)
        {
            if (!Url.StartsWith("http"))
            {
                Url = "http://www.playno1.com/" + Url;

            }
            if (!Directory.Exists(dir + "image"))
                Directory.CreateDirectory(dir + "image");

            var filename = dir + "image" + Path.DirectorySeparatorChar + Guid.NewGuid().ToString("N") + ".jpg";
            var Value = false;
            WebResponse response = null;
            Stream stream = null;

            try
            {
                Console.WriteLine(Url);
                var request = (HttpWebRequest) WebRequest.Create(Url);
                    
                    response = request.GetResponse();
                     SaveBinaryFile(response, filename);
                    return filename;
               
            }
            catch (System.Net.WebException e)
            {
                return string.Empty;
            }
         
        }

        private static bool SaveBinaryFile(WebResponse response, string fileName)
        {
            var Value = true;
            var buffer = new byte[1024];

            try
            {
                if (File.Exists(fileName))
                    File.Delete(fileName);
                Stream outStream = File.Create(fileName);
                var inStream = response.GetResponseStream();

                int l;
                do
                {
                    l = inStream.Read(buffer, 0, buffer.Length);
                    if (l > 0)
                        outStream.Write(buffer, 0, l);
                } while (l > 0);

                outStream.Close();
                inStream.Close();
            }
            catch
            {
                Value = false;
            }
            return Value;
        }
        public static string GetEntereScreenshot(IWebDriver _driver )
        {
            
            Bitmap stitchedImage = null;
            double totalwidth = (long)((IJavaScriptExecutor)_driver).ExecuteScript("return document.body.offsetWidth");//documentElement.scrollWidth");
            double totalHeight = (long)((IJavaScriptExecutor)_driver).ExecuteScript("return  document.body.scrollHeight");
            

            double viewwidth = (long)((IJavaScriptExecutor)_driver).ExecuteScript("return document.documentElement.clientWidth");//documentElement.scrollWidth");
            double viewHeight= (long)((IJavaScriptExecutor)_driver).ExecuteScript("return  document.documentElement.clientHeight");

            int page = (int)Math.Ceiling(totalHeight / viewHeight);
            
            var filename = Guid.NewGuid().ToString("N");
            for (int i = 0; i <=page; i++)
            {
                _driver.ExecuteJavaScript("window.scroll(0,"+ i * viewHeight + ")");
                Thread.Sleep(1000);
                _driver.TakeScreenshot().SaveAsFile( "screenshot"+Path.DirectorySeparatorChar+filename+ "-"+i+".png", ImageFormat.Png);

            }
            return filename;
        }
        public static Bitmap BytesToBitmap(byte[] Bytes)
        {
            MemoryStream stream = null;
            try
            {
                stream = new MemoryStream(Bytes);
                return new Bitmap((Image)new Bitmap(stream));
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }
        #region 合并图片
        /// <summary>
        /// 合并图片
        /// </summary>
        /// <param name="maps"></param>
        /// <returns></returns>
        private static  Bitmap MergerImg(List<Bitmap> maps)
        {
            int i = maps.Count;
            if (i == 0)
                throw new Exception("图片数不能够为0");
            //创建要显示的图片对象,根据参数的个数设置宽度
            Bitmap backgroudImg = new Bitmap(i * 12, 16);
            Graphics g = Graphics.FromImage(backgroudImg);
            //清除画布,背景设置为白色
            g.Clear(System.Drawing.Color.White);
            for (int j = 0; j < i; j++)
            {
                g.DrawImage(maps[j], j * 11, 0, maps[j].Width, maps[j].Height);
            }
            g.Dispose();
            return backgroudImg;
        }
        #endregion
        
        /// <summary>
        /// 合并图片
        /// </summary>
        /// <param name="bitMapDic"></param>
        /// <returns></returns>
        private Bitmap MergerImg(Dictionary<string, Bitmap> bitMapDic)
        {
            if (bitMapDic == null || bitMapDic.Count == 0)
                throw new Exception("图片数不能够为0");
            //创建要显示的图片对象,根据参数的个数设置宽度
            Bitmap backgroudImg = new Bitmap(bitMapDic.Count * 12, 16);
            Graphics g = Graphics.FromImage(backgroudImg);
            //清除画布,背景设置为白色
            g.Clear(System.Drawing.Color.White);
            int j = 0;
            foreach (KeyValuePair<string, Bitmap> entry in bitMapDic)
            {
                Bitmap map = entry.Value;
                g.DrawImage(map, j * 11, 0, map.Width, map.Height);
                j++;
            }
            g.Dispose();
            return backgroudImg;
        }
    }
}